import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import Taro from "@tarojs/taro";
import { addNumber } from "./counter";

export const getHomeData = createAsyncThunk(
  "get/homeData",
  async (extraInfo, { dispatch }) => {
    return new Promise((resolve, reject) => {
      console.log(extraInfo, "@@@");

      Taro.request({
        url: "http://codercba.com:9060/beike/api/powerscreen",
        success(res) {
          // 这里可以触发其它的 模块的action
          dispatch(addNumber(2));
          resolve(res.data);
          return res.data;
        },
        fail(err) {
          reject(err);
        },
      });
    });
  }
);

const homeSlice = createSlice({
  name: "home", // home/changeHomeData 作为action的type
  initialState: {
    homeData: {},
  },
  reducers: {
    // 局部的 state
    changeHomeData(state, { payload }) {
      state.homeData = payload;
    },
  },
  // 监听异步action的完成
  extraReducers: (builder) => {
    builder.addCase(getHomeData.fulfilled, (state, { payload }) => {
      state.homeData = payload;
    });
  },
});

export const { changeHomeData } = homeSlice.actions;
export default homeSlice.reducer;
